<template>
  <div class="jbc-container jbc-activity">
    <jbc-menu />
    <div class="jbc-activity__body">
      <div>
        <el-breadcrumb v-if="pathList.length" style="margin-top: 5px;padding: 12px 0 17px;"
          :separator-icon="ArrowRight">
          <el-breadcrumb-item v-for="path in pathList" :key="path.id" :to="path.url">{{ path.name
            }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="jbc-activity__section">
        <div class="jbc-activity__header">
          <div class="jbc-activity-img">
            <el-image style="width: 100%; height: 100%" :src="goodsInfo.pic" fit="cover"></el-image>
            <span v-if="false" class="jbc-activity-tag" :class="`jbc-activity-tag__${goodsInfo.state}`">{{
              goodsInfo.stateDisplay
            }}</span>
          </div>
          <div class="jbc-activity--info">
            <div class="jbc-activity--title">{{ goodsInfo.name }}</div>
            <div class="jbc-activity--time">分货时间： {{ goodsInfo.timeRange }} </div>
            <div class="jbc-activity--areas">分货区域： {{ goodsInfo.areaNames }}</div>
          </div>
        </div>
        <!-- <div class="jbc-activity__article" v-html="goodsInfo.bz"></div> -->
      </div>
      <div class="jbc-activity__list">
        <div class="sku-goods" v-for="(sku, index) in goodsInfo.skus" :key="index">
          <div class="sku-goods-img">
            <el-image style="width: 188px; height: 189px" :src="sku.coverimgurl" fit="cover"></el-image>
          </div>
          <div class="sku-goods-title">
            <el-text style="--el-text-font-size: var(--el-font-size-medium);color: var(--jbc-font-color)"
              line-clamp="2">{{
                sku.title }}</el-text>
          </div>
          <div class="sku-goods-desc">
            <div>单笔购买数量限制：{{ sku.minCount }}-{{ sku.oneCount }}</div>
            <el-text tag="div" truncated>
              分货总量：{{ sku.takeInventory }}(已售)/{{ sku.totalCount }}(总库存)
            </el-text>
          </div>
          <div class="sku-goods-footer">
            <div class="sku-goods-input">
              <el-input-number style="width: 100%;" v-model="sku.count" :min="sku.minCount" :max="sku.oneCount"></el-input-number>
            </div>
            <div class="sku-goods-btn">
              <el-button style="width: 100%;" color="#D6000F" @click="handleCommand('addIn', index)">加入本单</el-button>
            </div>
          </div>
        </div>
      </div>
      <transition>
        <div class="activity-cart" v-show="orderCar.skuDetails.length">
          <div class="activity-cart--header">
            <div class="activity-cart--title">分货活动待确认商品（{{ orderCar.skuDetails.length || 0 }}）</div>
          </div>
          <div class="activity-cart--body">
            <TransitionGroup name="list">
              <div class="activity-cart-goods" v-for="(goods, index) in orderCar.skuDetails" :key="index">
                <div class="activity-cart-goods--img">
                  <el-image style="width: 53px; height: 53px" :src="goods.coverimgurl" fit="cover"></el-image>
                </div>
                <div class="activity-cart-goods--info">
                  <el-text tag="div" class="activity-cart-goods--title" truncated>
                    {{ goods.title }}
                  </el-text>
                  <div class="activity-cart-goods--input"><el-input-number style="width: 100%;height: 29px;"
                      v-model="goods.count" :min="goods.minCount ? goods.minCount : 1" :max="goods.oneCount"></el-input-number></div>
                </div>
                <div class="activity-cart-goods--btn">
                  <el-button style="width: 100%;" @click="handleCommand('removeIn', goods.index)" text>删除</el-button>
                </div>
              </div>
            </TransitionGroup>
          </div>
          <div class="activity-cart--footer">
            <el-button color="#D6000F" @click="handleCommand('BuyNow')">生成分货订单</el-button>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script setup name="distributionActivity">
import { ArrowRight } from "@element-plus/icons-vue"
import { appViewLikeGet, appViewFollowGet, appViewAddCarsGet } from '@/api/goods'
import { appDistributionGetIdGet } from '@/api/common'
import { computed, reactive } from 'vue'
import { dialogCustomStyle } from '@/components/webCustom/utils'
import useClipboard from 'vue-clipboard3'
import { appOrderAddPost } from '@/api/order'
import { dayjs } from 'element-plus'
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()
const pathList = ref([{ id: '-1', name: '首页', url: '/' }, { id: '1', name: '分货活动', url: '/distribution' }, { id: '1', name: '分货活动详情' }])
const goodsInfo = ref({ skus: [] })
const stateMap = {
  0: '待开启',
  1: '进行中',
  2: '已结束',
  3: '已参加'
}
const orderCar = computed(() => {
  return {
    activityId: route.params.id,
    skuDetails: goodsInfo.value.skus.filter(sku => sku.in)
  }
})
route.params.id && appDistributionGetIdGet({ params: { id: route.params.id } }).then((res) => {
  res.data.timeRange = `${dayjs(res.data.stime).format('YYYY.MM.DD HH:mm:ss')}~${dayjs(res.data.etime).format('YYYY.MM.DD  HH:mm:ss')}`
  res.data.stateDisplay = stateMap[res.data.state]
  res.data.skus.forEach((sku, i) => {
    sku.count = 0
    sku.index = i
    sku.in = false
  })
  goodsInfo.value = res.data
}).catch((err) => {
  console.log(err)
})
const state = reactive({
  count: 1,
  id: route.params.id
})
const loading = ref(false)
const { toClipboard } = useClipboard()
const handleCommand = (type, r) => {
  switch (type) {
    case 'Like':
      appViewLikeGet({ params: { actionType: 2, valId: state.id } }).then((res) => {
        goodsInfo.value.isLike = res.data
        proxy.$modal.msgSuccess(`成功${res.data === 'Y' ? '' : '取消'}点赞`)
      }).catch((err) => {
      })
      break;
    case 'Follow':
      appViewFollowGet({ params: { actionType: 2, valId: state.id } }).then((res) => {
        goodsInfo.value.isfollow = res.data
        proxy.$modal.msgSuccess(`成功${res.data === 'Y' ? '' : '取消'}收藏`)
      }).catch((err) => {
      })
      break;
    case 'Share':
      proxy.$modal.confirm(
        `<div style="font-weight: bold;font-size: 16px;color: #323232;line-height: 21px;">复制链接分享商品</div><div style="background-color: #F5F6F5;font-size: 16px;color: #323232;line-height: 21px;padding: 12px 18px;margin-top: 14px;">${window.location.href}</div>`,
        { title: "分享商品", type: '' },
        {
          dangerouslyUseHTMLString: true,
          draggable: true,
          customClass: 'custom-message-box',
          customStyle: dialogCustomStyle({ width: '572px' }),
          showClose: false,
          confirmButtonText: '复制链接',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '复制中...'
              toClipboard(window.location.href).then(flag => {
                console.log(flag)
                proxy.$modal.msgSuccess(`链接已复制成功`)
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }).catch(e => {
                console.log(e)
                proxy.$modal.msgError('链接已复制失败，请手动复制')
                instance.confirmButtonLoading = false
              })
            } else {
              done()
            }
          }
        }
      ).catch((err) => { console.log(err) })
      break;
    case 'BuyNow':
      if (orderCar.value.skuDetails.length === 0) {
        proxy.$modal.msgError('请选择要购买的商品')
        return
      }
      if (!goodsInfo.value.canBuy) {
        proxy.$modal.msgError('您当前不符合购买条件: 可能是区域限制或库存不足')
        return
      }
      if (goodsInfo.value.buy) {
        proxy.$modal.msgError('您当前已参加过该活动，不能重复购买')
        return
      }
      loading.value = true
      appOrderAddPost({ body: { type: 0, activityId: orderCar.value.activityId, skuDetails: orderCar.value.skuDetails.map(sku => ({ count: sku.count, skuId: sku.id })) } }).then(res => {
        loading.value = false
        router.push({ path: `/payment/${res.data}` })
      }).catch((err) => {
      }).finally(() => {
        loading.value = false
      })
      break;
    case 'addIn':
      if (goodsInfo.value.buy) {
        proxy.$modal.msgError('您当前已参加过该活动，不能重复购买')
        return
      }
      goodsInfo.value.skus[r].in = true
      break;
    case 'removeIn':
      goodsInfo.value.skus[r].in = false
      break;
    default:
      proxy.$modal.msg('敬请期待！')
      break;
  }
}
</script>

<style lang="scss" scoped>
.jbc-activity {
  &__body {
    width: var(--box-width);
    margin: 0 auto;
  }

  &__section {
    background: #FFFFFF;
    box-sizing: border-box;
  }

  &__header {}

  &-img {
    width: 1314px;
    height: 464px;
    position: relative;
  }

  &-tag {
    position: absolute;
    left: 0;
    top: 0;
    font-size: 16px;
    color: #FFFFFF;
    line-height: 30px;
    border-radius: 0px 0px 16px 0px;
    padding: 5px 20px 5px 15px;

    &__0 {
      background: #F78D00;
    }

    &__1 {
      background: #0FCEA4;
    }

    &__2 {
      background: #4B4949;
    }

    &__3 {
      background: #D6000F;
    }
  }

  &--info {
    padding: 26px 20px;

    & div~div {
      margin-top: 12px;
    }
  }

  &--title {
    font-weight: bold;
    font-size: var(--jbc-font-size-extra-large);
    color: var(--jbc-font-color);
    line-height: 26px;
  }

  &--time,
  &--areas {
    font-size: var(--jbc-font-size-medium);
    color: var(--jbc-font-color-light);
    line-height: 21px;
  }

  &__article {
    background-position: 0 0;
    background-repeat: no-repeat;
    background-size: 100%;
  }

  &__list {
    display: flex;
    flex-wrap: wrap;

    .sku-goods {
      margin-top: 20px;
      margin-left: 19px;
      width: 247px;
      background-color: #FFFFFF;
      border: 1px solid #EBEBEB;

      &:nth-child(5n+1) {
        margin-left: 0;
      }

      &-img {
        padding: 29px 29px 29px 30px;
        position: relative;
      }

      &-title {
        padding: 12px 19px 6px;
        height: 52px;
        box-sizing: content-box;
      }

      &-desc {
        padding: 6px 19px;
        font-size: var(--jbc-font-size-extra-small);
        color: var(--jbc-font-color-light);
        line-height: 16px;

        & div~div {
          margin-top: 6px;
          font-size: var(--jbc-font-size-extra-small);
          color: var(--jbc-font-color-light);
        }
      }

      &-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 19px 19px 20px;

        .el-button--default {
          padding: 12px 5px
        }
      }

      &-btn {
        margin-left: 10px;
      }

      &-input {
        flex: 1;
      }
    }
  }
}

.activity-cart {
  position: fixed;
  width: 303px;
  left: 0px;
  top: 277px;
  box-sizing: border-box;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0px 2px 10px 0px rgba(204, 204, 204, 0.5);
  border-radius: 0px 20px 20px 0px;
  z-index: 9999;

  &--title {
    font-weight: bold;
    font-size: 16px;
    color: #323232;
    line-height: 21px;
  }

  &-goods {
    display: flex;
    align-items: flex-start;
    padding: 14px 0;

    &~& {
      border-top: 1px solid #EBEBEB;
    }

    &--img {
      width: 55px;
      height: 55px;
      background: #FFFFFF;
      border: 1px solid #EBEBEB;
      box-sizing: border-box;
      margin-right: 12px;
    }

    &--info {
      flex: 1;
      width: 1px;
    }

    &--title {
      font-size: 12px;
      color: #323232;
      line-height: 16px;
    }

    &--input {
      margin-top: 5px;
    }

    &--btn {
      margin-left: 12px;
    }
  }

  &--footer {
    margin-top: 6px;

    .el-button {
      width: 100%;
      height: 29px;
    }
  }
}

:deep(.el-input-number--default) {
  --el-border: 1px solid var(--jbc-border-color);

  .el-input-number__decrease,
  .el-input-number__increase {
    background-color: #fff;
  }
}

:deep(.jbc-activity__article) {
  img {
    max-width: 100%;
  }
}

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style>